import defaultAvatar from '@/images/logo.jpg';
import ImgCrop from 'antd-img-crop';
import {
  FamousPersonInfo,
  getFamousPersonInfo,
  updateFamousPersonInfo,
} from '@/services/FamousPersonService';
import { PLAY_BASE_URL, uploadFile } from '@/services/FileService';
import {
  EditOutlined,
  EyeOutlined,
  RollbackOutlined,
  SaveOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  Form,
  Image,
  Input,
  Space,
  Tag,
  Upload,
  message,
} from 'antd';
import pinyin from 'pinyin';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
const { TextArea } = Input;
import { famousPersonId } from '@/services';
const ProfileAdmin: React.FC = () => {
  const [isEditing, setIsEditing] = useState(false);
  const [mode, setMode] = useState<'split' | 'edit' | 'preview'>('preview');
  const [avatarUrl, setAvatarUrl] = useState<string>();
  const [formData, setFormData] = useState<FamousPersonInfo>({} as FamousPersonInfo);
  const [form] = Form.useForm();

  // 生成拼音的函数
  const generatePinyin = (name: string) => {
    if (!name) return '';
    return pinyin(name, {
      style: pinyin.STYLE_NORMAL,
      heteronym: false, // 禁用多音字
    })
      .map((p) => p[0])
      .join(' '); // 移除 segment 选项
  };

  // 获取名人信息
  const fetchFamousPersonInfo = async () => {
    try {
      const data = await getFamousPersonInfo(famousPersonId);
      const pinyinStr = generatePinyin(data.name);
      const newData = {
        ...data,
        pinyin: pinyinStr,
      };
      setFormData(newData);
      form.setFieldsValue(newData);
      if (data.imageId) {
        setAvatarUrl(`${PLAY_BASE_URL}/${data.imageId}`);
      }
    } catch (error) {
      message.error('获取信息失败');
    }
  };

  // 处理表单值变化
  const handleFormValuesChange = (changedValues: any, allValues: any) => {
    if (isEditing) {
      // 保持原有的拼音值
      const currentPinyin = formData.pinyin;

      // 如果修改了名字，重新生成拼音
      if (changedValues.name !== undefined) {
        // 使用 undefined 判断，这样空字符串也能被检测到
        const pinyinStr = generatePinyin(changedValues.name || '');
        setFormData({
          ...allValues,
          pinyin: pinyinStr,
        });
      } else {
        // 其他字段修改时保持原有拼音
        setFormData({
          ...allValues,
          pinyin: currentPinyin,
        });
      }
    }
  };

  // 页面加载时获取名人信息
  useEffect(() => {
    fetchFamousPersonInfo();
  }, []);

  // 处理头像上传
  const handleAvatarChange = async (options: any) => {
    const { file, onSuccess, onError } = options;

    console.log(file)
    try {
      const fileId = await uploadFile(file);
      // 构建预览URL
      const previewUrl = `${PLAY_BASE_URL}/${fileId}`;
      setAvatarUrl(previewUrl);
      form.setFieldValue('imageId', fileId);
      onSuccess();
      message.success('上传成功');
    } catch (error) {
      onError(error);
      message.error('头像上传失败');
    }
  };

  // 修改表单提交的处理
  const handleSubmit = async (values: any) => {
    try {
      const submitData: FamousPersonInfo = {
        ...formData,
        ...values,
        id: famousPersonId,
        imageId: Number(form.getFieldValue('imageId')) || formData.imageId,
      };

      const response = await updateFamousPersonInfo(submitData);
      message.success('保存成功');
      setFormData(response);
      setIsEditing(false);
      setMode('preview');

      if (response.imageId) {
        setAvatarUrl(`/api/file/play/${response.imageId}`);
      }
    } catch (error) {
      message.error('保存失败');
      console.error('保存失败:', error);
    }
  };

  // 开始编辑
  const startEditing = () => {
    setIsEditing(true);
    setMode('split');
  };

  // 取消编辑
  const cancelEditing = () => {
    setIsEditing(false);
    setMode('preview');
    fetchFamousPersonInfo(); // 重新获取数据并更新表单
  };

  // 处理多种分隔符的字符串转换为数组
  const splitString = (str: string = '') => {
    // 将中文逗号替换为英文逗号，将顿号替换为英文逗号
    const normalizedStr = str.replace(/，/g, ',').replace(/、/g, ',');
    return normalizedStr
      .split(',')
      .map((item) => item.trim())
      .filter(Boolean);
  };

  // 渲染预览区域
  const renderPreview = () => {
    return (
      <div className={styles.preview}>
        <div className={styles.previewHeader}>
          <div className={styles.previewAvatar}>
            <Image
              src={avatarUrl || defaultAvatar}
              alt="头像"
              width={180}
              height={180}
              style={{ objectFit: 'cover', borderRadius: '50%' }}
              preview={false}
            />
          </div>
          <div className={styles.previewInfo}>
            <div className={styles.nameSection}>
              <h2>{formData.name || '未设置姓名'}</h2>
              <p className={styles.pinyin}>{formData.pinyin || '未设置拼音'}</p>
              <p className={styles.foreignName}>
                外文名：{formData.englishName || '未设置'}
              </p>
            </div>
            <div className={styles.tags}>
              {formData.occupation && splitString(formData.occupation).map((tag) => (
                <Tag key={tag} color="blue">
                  {tag}
                </Tag>
              ))}
            </div>
          </div>
        </div>

        <div className={styles.previewContent}>
          <div className={styles.previewSection}>
            <h3>个人简介</h3>
            <p>{formData.introduction || '暂无简介'}</p>
          </div>

          <div className={styles.previewSection}>
            <h3>基本信息</h3>
            <div className={styles.infoGrid}>
              <div className={styles.infoItem}>
                <span className={styles.label}>出生日期</span>
                <span className={styles.value}>{formData.birthDate || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>星座</span>
                <span className={styles.value}>{formData.constellation || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>生肖</span>
                <span className={styles.value}>{formData.zodiac || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>国籍</span>
                <span className={styles.value}>{formData.nationality || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>性别</span>
                <span className={styles.value}>{formData.gender || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>特长</span>
                <span className={styles.value}>{formData.specialTalent || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>兴趣爱好</span>
                <span className={styles.value}>{formData.hobbies || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>粉丝名称</span>
                <span className={styles.value}>{formData.fansName || '未设置'}</span>
              </div>
              <div className={styles.infoItem}>
                <span className={styles.label}>应援色</span>
                <span className={styles.value}>{formData.supportColor || '未设置'}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 渲染具栏
  const renderToolbar = () => (
    <Space>
      {!isEditing ? (
        <Button type="primary" icon={<EditOutlined />} onClick={startEditing}>
          编辑
        </Button>
      ) : (
        <>
          <Button
            type={mode === 'edit' ? 'primary' : 'default'}
            icon={<EditOutlined />}
            onClick={() => setMode('edit')}
          >
            仅编辑
          </Button>
          <Button
            type={mode === 'preview' ? 'primary' : 'default'}
            icon={<EyeOutlined />}
            onClick={() => setMode('preview')}
          >
            仅预览
          </Button>
          {mode !== 'split' && (
            <Button onClick={() => setMode('split')}>分屏显示</Button>
          )}
        </>
      )}
    </Space>
  );

  // 在组件初始化或编辑时，如果有 imageId，需要置预览图
  useEffect(() => {
    if (formData.imageId) {
      setAvatarUrl(`/api/file/play/${formData.imageId}`);
    }
  }, [formData.imageId]);

  return (
    <div className={styles.pageContainer}>
      <div className={styles.toolbar}>{renderToolbar()}</div>
      <div className={`${styles.container} ${styles[mode]}`}>
        {/* 编辑区域 */}
        {mode !== 'preview' && (
          <Card
            className={styles.editSection}
            title="编辑区域"
            extra={
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SaveOutlined />}
                  onClick={() => {
                    console.log('save button clicked');
                    form
                      .validateFields()
                      .then((values) => {
                        console.log('form values:', values);
                        handleSubmit(values);
                      })
                      .catch((err) => {
                        console.error('Validation failed:', err);
                      });
                  }}
                >
                  保存
                </Button>
                <Button icon={<RollbackOutlined />} onClick={cancelEditing}>
                  取消
                </Button>
              </Space>
            }
          >
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              onValuesChange={handleFormValuesChange}
              initialValues={formData} // 添加初始值
            >
              <Form.Item
                label="头像"
                name="imageId"
                // 头像组件大小再大一些
                rules={[{ required: true, message: '请上传头像' }]}
              >
                <div className={styles.avatarContainer}>
                  <ImgCrop
                    rotationSlider
                    quality={1}
                    modalTitle="裁剪头像"
                    modalOk="确定"
                    modalCancel="取消"
                    cropShape="round"
                    // 裁剪途中不影响原头像
                    onModalCancel={() => {
                      setAvatarUrl(localStorage.getItem('avatarUrl') || '');
                    }}


                  >
                    <Upload
                      name="avatar"
                      listType="picture-circle"
                      className={styles.avatarUploader}
                      showUploadList={false}
                      customRequest={handleAvatarChange}
                    >
                      <div
                        style={{
                          width: '100%',
                          height: '100%',
                          position: 'relative',
                        }}
                      >
                        <Image
                          src={avatarUrl || defaultAvatar}
                          alt="头像"
                          width="100%"
                          height="100%"
                          style={{ objectFit: 'cover', borderRadius: '50%' }}
                          preview={false}
                        />
                        <div className={styles.avatarMask} onClick={() => {
                          localStorage.setItem('avatarUrl', avatarUrl || '');
                        }}>
                          <UploadOutlined />
                          <div>更换头像</div>
                        </div>
                      </div>
                    </Upload>
                  </ImgCrop>
                </div>
              </Form.Item>

              <Form.Item
                label="姓名"
                name="name"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input maxLength={20} />
              </Form.Item>

              <Form.Item
                label="外文名"
                name="englishName"
                rules={[{ required: true, message: '请输入外文名' }]}
              >
                <Input maxLength={20} placeholder="多个外名用逗号分隔" />
              </Form.Item>

              <Form.Item
                label="简介"
                name="introduction"
                rules={[{ required: true, message: '请输入简介' }]}
              >
                <TextArea rows={4} maxLength={255} showCount />
              </Form.Item>

              <Form.Item
                label="出生日期"
                name="birthDate"
                rules={[{ required: true, message: '请选择出生日期' }]}
              >
                <Input type="date" />
              </Form.Item>

              <Form.Item label="星座" name="constellation">
                <Input maxLength={20} />
              </Form.Item>

              <Form.Item label="生肖" name="zodiac">
                <Input maxLength={20} />
              </Form.Item>

              <Form.Item label="特长" name="specialTalent">
                <Input maxLength={50} placeholder="多个特长用逗号分隔" />
              </Form.Item>

              <Form.Item label="国籍" name="nationality">
                <Input maxLength={50} />
              </Form.Item>

              <Form.Item label="性别" name="gender">
                <Input maxLength={10} />
              </Form.Item>

              <Form.Item label="职业" name="occupation">
                <Input maxLength={50} placeholder="多个职业用逗号分隔" />
              </Form.Item>

              <Form.Item label="兴趣爱好" name="hobbies">
                <Input maxLength={255} placeholder="多个兴趣用逗号分隔" />
              </Form.Item>

              <Form.Item label="粉丝名称" name="fansName">
                <Input maxLength={255} />
              </Form.Item>

              <Form.Item label="应援色" name="supportColor">
                <Input maxLength={50} />
              </Form.Item>
            </Form>
          </Card>
        )}

        {/* 预览区域 - 修改这里 */}
        {mode !== 'edit' && (
          <Card
            className={styles.previewSection}
            title={isEditing ? '预览区域' : null} // 只在编辑模式下显示标题
            bordered={isEditing} // 只在编辑模式下显示边框
          >
            {renderPreview()}
          </Card>
        )}
      </div>
    </div>
  );
};

export default ProfileAdmin;
